/*
 * Copyright 2011-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.commons.util.okhttp.ssl;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * HTTPS 支持
 *
 * @author liym
 * @since 2017-12-20 12:37 新建
 */
public final class SSLContextUtil {

    private SSLContextUtil() {}

    private final static TrustManager[] TRUST_ALL_CERTS = new X509TrustManager[]{new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {}

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {}

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }};

    /**
     * 获取  X509TrustManager
     *
     * @return {@link X509TrustManager}
     * @see okhttp3.OkHttpClient.Builder#sslSocketFactory(javax.net.ssl.SSLSocketFactory, javax.net.ssl.X509TrustManager)
     * @since 2017-12-20 13:04:29
     */
    public static X509TrustManager getTrustManager() {
        TrustManagerFactory trustManagerFactory;
        String algorithm = TrustManagerFactory.getDefaultAlgorithm();
        try {
            trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
            trustManagerFactory.init((KeyStore) null);
        } catch (NoSuchAlgorithmException e) { // TrustManagerFactory.getInstance
            throw new IllegalStateException("NoSuchAlgorithm: " + algorithm, e);
        } catch (KeyStoreException e) { // trustManagerFactory.init
            throw new IllegalStateException("KeyStore error", e);
        }
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
        return (X509TrustManager) trustManagers[0];
    }

    /**
     * 获取 “全部信任” 的 SSLSocketFactory
     *
     * @return Trust All 'SSLSocketFactory'
     * @since 2017-12-20 12:41:34
     */
    public static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssf = null;
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, TRUST_ALL_CERTS, new SecureRandom());
            ssf = context.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssf;
    }

}
